package com.licq.ldoc;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.licq.ldoc.scanner.ClassScanner;
import com.licq.ldoc.writer.Writer;
import com.licq.ldoc.writer.impl.DocWriter;

/**
 * 
 * @author liujian
 *
 */
public class LDocConsole {

	private static final String STRING_SPACE = " ";

	private static final String DEFAULT_JAR_PATH = "lib/derbysoft/derbysoft-remote.jar";
	
	private static final String DEFAULT_FILE_NAME = "ldoc";
	
	private static BufferedReader in;

	public static void execute(String[] args) throws Exception {
		in = new BufferedReader(new InputStreamReader(System.in));
		configPaths(args[0]);
		List<String> patterns = Arrays.asList(args[1].split(","));
		String outdir = args[2];
		String filename = args[3];
		doc(patterns, outdir, filename);
	}

	@SuppressWarnings("unused")
	private static String getInputFileName() throws Exception {
		System.out.println("输入文档名(默认ldoc):");
		String filename = in.readLine();
		if (StringUtils.isBlank(filename)) {
			filename = DEFAULT_FILE_NAME;
		}
		return filename;
	}

	@SuppressWarnings("unused")
	private static String getInputOutdir() throws Exception {
		System.out.println("输入文档输出目录(默认%LDoc_PATH%):");
		String outdir = in.readLine();
		if (StringUtils.isBlank(outdir)) {
			outdir = Environment.PROJECT_PATH;
		}
		return safeSlashPath(outdir);
	}

	@SuppressWarnings("unused")
	private static List<String> getInputPatterns() throws Exception {
		System.out.println("输入需要解析的类的匹配规则， 以空格分隔(e.g. com/derby/**/*RQ.class):");
		String patterns = in.readLine();
		List<String> validPatterns = getValidPatterns(patterns);
		if (CollectionUtils.isEmpty(validPatterns)) {
			System.out.println("输入无效!");
			return getInputPatterns();
		}
		return validPatterns;
	}

	private static List<String> getValidPatterns(String patterns) {
		List<String> validPatterns = new ArrayList<String>();
		String[] patternArray = StringUtils.split(patterns, STRING_SPACE);
		for (String pattern : patternArray) {
			if (!pattern.endsWith(".class")) {
				return null;
			} else {
				validPatterns.add(safeSlashPath(pattern));
			}
		}
		return validPatterns;
	}

	private static void configPaths(String paths) throws Exception {
		List<String> validPaths = getValidPaths(paths);
		if (CollectionUtils.isEmpty(validPaths)) {
			System.out.println("输入无效!");
            return;
        }
		completePaths(validPaths);
		String[] pathArray = (String[]) validPaths.toArray(new String[validPaths.size()]);
		System.setProperty(Environment.JAVA_CLASS_PATH, new StringBuilder(Environment.CLASS_PATHS)
			.append(Environment.PATH_SEPARATOR)
			.append(StringUtils.join(pathArray, Environment.PATH_SEPARATOR))
			.toString());
	}
	
	private static List<String> getValidPaths(String paths) {
		List<String> validPaths = new ArrayList<String>();
		String[] pathArray = StringUtils.split(paths, STRING_SPACE);
		if (pathArray == null) {
			return null;
		}
		for (String path : pathArray) {
			if (!path.endsWith(".jar")) {
				return null;
			} else {
				validPaths.add(path);
			}
		}
		if (validPaths.isEmpty()) {
			validPaths.add(DEFAULT_JAR_PATH);
		}
		return validPaths;
	}

	private static void doc(List<String> patterns, String outdir, String filename) 
		throws Exception {
		File dir = new File(outdir);
		if (!dir.exists() || !dir.isDirectory()) {
			if (!dir.mkdirs()) {
				System.out.println(String.format("create the out directory[%s] failed.", 
						outdir
					)
				);
				System.exit(-1);
			}
		}
		LDoc doc = new LDoc(
    		new ClassScanner(StringUtils.join(patterns, ",")), 
            new Writer[] {
            	new DocWriter(String.format("%s/%s.pdf", outdir, filename)),
            	new DocWriter(String.format("%s/%s.rtf", outdir, filename)),
            	new DocWriter(String.format("%s/%s.html", outdir, filename))
            }
        );
        doc.process();
	}

	/**
	 * allow path relative to the project root path
	 * @param paths
	 */
	private static void completePaths(List<String> paths) {
		for (int i = 0; i < paths.size(); i++) {
			String path = paths.get(i);
			if (!path.contains(":") && !path.startsWith("/")) {
				//complete relative path
				path = Environment.PROJECT_PATH + "/" + path;
			}
			paths.set(i, safeSlashPath(path));
		}
	}
	
	private static String safeSlashPath(String path) {
		return path.replaceAll("\\\\", "/");
	}
	
	public static void main(String[] args) {
		String s = "com\\wise\\demo";
		System.out.println(safeSlashPath(s));
	}
	
}
